package com.paomi.client.fragment.first.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.paomi.client.GlideApp;
import com.paomi.client.GlideOptions;
import com.paomi.client.R;
import com.paomi.client.activity.detail.DetailTicketActivity;
import com.paomi.client.activity.newsDetail.NewsDetailActivity;
import com.paomi.client.activity.person.model.TaskListBean;
import com.paomi.client.base.BaseLoadMorePresenter;
import com.paomi.client.base.BaseMvpLCEView;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.fragment.first.model.BannerBean;
import com.paomi.client.fragment.first.model.BannerJsonBean;
import com.paomi.client.fragment.first.model.NewsJson;
import com.paomi.client.activity.newsDetail.model.NewsListJson;
import com.paomi.client.fragment.first.model.TicketJson;
import com.paomi.client.fragment.first.model.TicketListJson;
import com.paomi.client.fragment.first.model.XBannerJson;
import com.paomi.client.fragment.mine.model.SignDataBean;
import com.paomi.client.net.Api;
import com.paomi.client.net.BaseCallback;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.CornerTransform;
import com.paomi.client.utils.Datas;
import com.paomi.client.utils.GlideRoundTransform;
import com.paomi.client.utils.Util;
import com.paomi.client.view.HorizontalBanner;
import com.paomi.client.view.HorizontalNewBanner;
import com.paomi.client.view.SignInDialog;
import com.paomi.client.view.banner.xbanner.XBanner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * Created by pc on 2018/10/25
 * Describe:
 * com.paomi.client.fragment.first.presenter
 */
public class FirstFraPre extends BaseLoadMorePresenter<BaseMvpLCEView> {
    List<BannerJsonBean> bannerList = new ArrayList<>();
    List<String> imgList = new ArrayList<>();
    List<XBannerJson> bannerInfo = new ArrayList<>();
    private List<TicketJson> ticketJsonList = new ArrayList();
    private List<NewsListJson> newsJsonList = new ArrayList();
    private int pageNme = 1;
    private Context mContext;

    /**
     * 首页轮播广告
     */
    public void setBannerList(HorizontalBanner getBanner, Context context, HorizontalNewBanner horizontalNewBanner) {
        mContext=context;
        Api.getInstanceService(Constants.BASE_URL).getBannerList().enqueue(new BaseCallback<BannerBean>() {
            @Override
            public void onResponse(Call<BannerBean> call, BannerBean result) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
//                        EventBus.getDefault().post(result);
                        setBannerShow(result, getBanner, context,horizontalNewBanner);
                    }
                }, 100);
            }
        });

    }

    /**
     * 数据解析以及展示轮播
     *
     * @param result
     * @param firstBanner
     */
    private void setBannerShow(BannerBean result, HorizontalBanner firstBanner, Context mcontext, HorizontalNewBanner horizontalNewBanner) {
        bannerList.clear();
        ticketJsonList.clear();
        newsJsonList.clear();
        Gson gson = new Gson();
        Map<String, Object> map = null;
        String json = Datas.toJsonString(result.getReturnData());
        try {
            map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {
            }.getType());
            // json转为带泛型的list
            if (map.size() > 0) {
                if (map.containsKey("0")) {//轮播图
                    String map0 = gson.toJson(map.get("0"));
                    List<BannerJsonBean> retList = gson.fromJson(map0,
                            new TypeToken<List<BannerJsonBean>>() {
                            }.getType());
                    bannerList.addAll(retList);
                }
                if (map.containsKey("1")) {// 精彩演出
                    String map1 = gson.toJson(map.get("1"));
                    List<TicketJson> retList1 = gson.fromJson(map1,
                            new TypeToken<List<TicketJson>>() {
                            }.getType());
                    ticketJsonList.addAll(retList1);
                }
                if (map.containsKey("2")) {//热门资讯
                    String map2 = gson.toJson(map.get("2"));
                    List<NewsListJson> retList2 = gson.fromJson(map2,
                            new TypeToken<List<NewsListJson>>() {
                            }.getType());
                    newsJsonList.addAll(retList2);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //精彩演出
        TicketListJson.TicketList ticketList = new TicketListJson.TicketList();
        ticketList.setData(ticketJsonList);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                EventBus.getDefault().post(ticketList);
            }
        }, 1000);
        //热门资讯
        NewsJson newsJson = new NewsJson();
        NewsJson.NewsBean newsBean = new NewsJson.NewsBean();
        newsBean.setData(newsJsonList);
        newsJson.setReturnData(newsBean);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                EventBus.getDefault().post(newsJson);
            }
        }, 1000);
        //轮播图
        imgList.clear();
        bannerInfo.clear();
        if (bannerList.size() > 0) {
            for (BannerJsonBean bannerJsonBean : bannerList) {
                imgList.add(bannerJsonBean.getImg_url());
                XBannerJson xBannerJson=new XBannerJson();
                xBannerJson.setUrl(bannerJsonBean.getImg_url());
                bannerInfo.add(xBannerJson);
            }
        }
        horizontalNewBanner.setBannerData(R.layout.layout_custom_view, bannerInfo);
        horizontalNewBanner.getViewPager().getAdapter().notifyDataSetChanged();
        //加载广告图片
        horizontalNewBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ImageView iv = view.findViewById(R.id.iv_banner);
                GlideApp.with(mContext).asBitmap().load(bannerInfo.get(position).getUrl()).placeholder(R.mipmap.img_default_banner).into(iv);
            }
        });

        //顶部banner点击事件
        horizontalNewBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                if (bannerInfo.size() == 0) {
                    return;
                }
                BannerJsonBean bean = bannerList.get(position);
                String type = bean.getJump_type();//跳转类型 0演出 1衍生品 2资讯 3第三方链接
                switch (type) {
                    case "0"://演出
                        Intent intent = new Intent(mcontext, DetailTicketActivity.class);
                        intent.putExtra("getId", "" + bean.getUri());
                        mcontext.startActivity(intent);
                        break;
                    case "1"://衍生品
                        break;
                    case "2"://资讯
                        Intent intent1 = new Intent(mcontext, NewsDetailActivity.class);
                        intent1.putExtra("newId", "" + bean.getUri());
                        mcontext.startActivity(intent1);
                        break;
                    case "3"://第三方链接
                        break;
                }

            }
        });
//        firstBanner.setImageLoader(new GlideImageLoader());
//        firstBanner.setImages(imgList);
//        //设置banner指示器 可选择样式
//        firstBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
//        //设置banner指示器位置
//        firstBanner.setIndicatorGravity(BannerConfig.CENTER);
//        //设置轮播时间
//        firstBanner.setDelayTime(2500);
//        //banner设置方法全部调用完毕时最后调用
//        firstBanner.start();
//
//        firstBanner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(final int position) {
//                BannerJsonBean bean = bannerList.get(position);
//                String type = bean.getJump_type();//跳转类型 0演出 1衍生品 2资讯 3第三方链接
//                switch (type) {
//                    case "0"://演出
//                        Intent intent = new Intent(mcontext, DetailTicketActivity.class);
//                        intent.putExtra("getId", "" + bean.getUri());
//                        mcontext.startActivity(intent);
//                        break;
//                    case "1"://衍生品
//                        break;
//                    case "2"://资讯
//                        Intent intent1 = new Intent(mcontext, NewsDetailActivity.class);
//                        intent1.putExtra("newId", "" + bean.getUri());
//                        mcontext.startActivity(intent1);
//                        break;
//                    case "3"://第三方链接
//                        break;
//                }
//            }
//        });
    }


    /**
     * 售票列表的数据请求
     * 参数名	是否必选	注释
     * content	true	搜索内容
     * pageNum	true	页码
     * pageSize false	每页展示数量(默认10)
     * sort	false	排序规则(默认0) 0 时间 1 热度
     */
//    public void setTicketJsonList(String pageNum) {
//        Map<String, String> stringMap = new HashMap<>();
//        stringMap.put("content", "");
//        stringMap.put("pageNum", pageNum);
//        stringMap.put("pageSize", "" + Constants.PAGE_SIZE);
//        stringMap.put("sort", "0");
//        Api.getInstanceService(Constants.Ticket_URL).getSearchTicket(stringMap).enqueue(new BaseCallback<TicketListJson>() {
//            @Override
//            public void onResponse(Call<TicketListJson> call, TicketListJson result) {
//                new Handler().postDelayed(new Runnable() {
//                    public void run() {
//                        EventBus.getDefault().post(result.getReturnData());
//                    }
//                }, 100);
//            }
//        });
//    }

//    public void setLoadNewsData(int pageN) {
//        pageNme = pageN;
//    }

    /**
     * 资讯列表的数据请求
     *
     * @param page          当前要请求的页数
     * @param skip          当前开始的数据索引
     * @param pullToRefresh 是否是下拉刷新
     */
    @Override
    protected void loadData(int page, int skip, boolean pullToRefresh) {
//        Map<String, String> stringMap = new HashMap<>();
//        stringMap.put("content", "");
//        stringMap.put("pageNum", "" + pageNme);
//        stringMap.put("pageSize", "" + Constants.PAGE_SIZE);
//        stringMap.put("sort", "0");
//        if (pageNme == page) {
//            Api.getInstanceService(Constants.Ticket_URL).getSearchNews(stringMap).enqueue(new BaseCallback<NewsJson>() {
//                @Override
//                public void onResponse(Call<NewsJson> call, NewsJson result) {
//                    new Handler().postDelayed(new Runnable() {
//                        public void run() {
//                            EventBus.getDefault().post(result);
//                        }
//                    }, 1000);
//                }
//            });
//        }

    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            imageView.setAdjustViewBounds(true);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            //清除所有内存缓存(圆角与图片自适应相冲突)
//            GlideApp.get(context).clearMemory();
//            GlideApp.with(context).asBitmap().load(path).placeholder(R.mipmap.img_default_banner).skipMemoryCache(false).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
//                    .transform(new CornerTransform(mContext,Util.dip2px(mContext,5f))).into(imageView);
            RequestOptions myOptions = new RequestOptions()
                    .fitCenter()
                    .transform(new GlideRoundTransform(context,5));
//            GlideApp.with(context).asBitmap().load(path).placeholder(R.mipmap.img_default_banner).apply(myOptions).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).into(imageView);
            GlideApp.with(context).asBitmap().load(path).placeholder(R.mipmap.img_default_banner).apply(myOptions).into(imageView);
        }

        //提供createImageView 方法，如果不用可以不重写这个方法，主要是方便自定义ImageView的创建
        @Override
        public ImageView createImageView(Context context) {
            //使用fresco，需要创建它提供的ImageView，当然你也可以用自己自定义的具有图片加载功能的ImageView
            return super.createImageView(context);
        }
    }

    /**
     * 获取积分任务列表判断是否签到
     */
    public void getTaskList() {
        Api.getInstanceService(Constants.User_URL).getTaskList().enqueue(new BaseCallback<TaskListBean>() {
            @Override
            public void onResponse(Call<TaskListBean> call, TaskListBean result) {
                EventBus.getDefault().post(result);
            }
        });
    }

    /**
     * 积分-完成任务
     */
    public void toSign() {
        Api.getInstanceService(Constants.User_URL).taskComplete("1").enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                EventBus.getDefault().post("SignSuccess");
            }
        });
    }

    private SignInDialog dialog;

    /**
     * 签到弹出框的显示
     */
    public void getSignDialog(Context context) {
        dialog = new SignInDialog(context);
        //得到当前的年或月
        Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR); // 获取当前年份
        int mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        Api.getInstanceService(Constants.User_URL).getSign("" + mYear, "" + mMonth).enqueue(new BaseCallback<SignDataBean>() {
            @Override
            public void onResponse(Call<SignDataBean> call, SignDataBean result) {
                if (result.getReturnData() != null) {
                    dialog.creatDialog(mYear, mMonth, result.getReturnData().getData()).show();
                }
            }
        });
    }
}
